package com.franklin.ideaplugin.easytesting.controllerclient.request;

import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.controllerclient.beans.MethodData;
import com.franklin.ideaplugin.easytesting.controllerclient.beans.RequestData;

/**
 * @author Ye Junhui
 * @since 2023/6/29
 */
public class DefaultRequestBuilder implements IRequestBuilder {

    @Override
    public RequestData buildRequest(MethodData methodData, String[] parameterNames, Object[] args) {
        RequestData requestData = new RequestData();

        //基本数据
        processBaseData(methodData,requestData);

        //参数
        processArgument(requestData,methodData,parameterNames,args);
        return requestData;
    }

    private void processBaseData(MethodData methodData,RequestData requestData){
        //路径
        requestData.setUrl(methodData.getUrl());

        //请求方法
        requestData.setHttpMethod(methodData.getHttpMethod());

        //请求头
        requestData.getHttpHeaders().addAll(methodData.getMethodHeaders());
    }

    /**
     * 处理参数
     * @param requestData
     * @param methodData
     * @param parameterNames
     * @param args
     */
    private void processArgument(RequestData requestData,MethodData methodData, String[] parameterNames, Object[] args){
        Class<?>[] parameterTypes = methodData.getMethod().getParameterTypes();
        for (int i = 0; i < args.length; i++) {
            String parameterName = parameterNames[i];
            String paramNameFromAnnotation = methodData.getParamKeys().get(i);
            if (StrUtil.isNotBlank(paramNameFromAnnotation) && !paramNameFromAnnotation.equals(String.valueOf(i))){
                //从注解中取到指定的参数名
                parameterName = paramNameFromAnnotation;
            }
            RequestPosition requestPosition = methodData.getParamPositions().getOrDefault(i, RequestPosition.IGNORE);
            requestPosition.fill(requestData,parameterName,parameterTypes[i] , args[i]);
        }
    }
}
